/*
 * Copyright 2017 Yan Zhenjie
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yingpai.fitness.dvp_2_0.common.view.statusbar;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Point;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.view.Display;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewConfiguration;

import com.orhanobut.logger.Logger;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * Created by YanZhenjie on 2017/12/13.
 */
public class MeasureView extends View {

    private static boolean isInitialize = false;

    public static int sStatusBarHeight = 0;
    public static int sNavigationBarHeight = 0;

    private static final String NAVIGATION_GESTURE = "force_fsg_nav_bar";
    private static final int NAVIGATION_GESTURE_OFF = 0;

    private static void measureScreenSize(Context context) {
        if (isInitialize) return;
        isInitialize = true;

//        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
//        Display display = windowManager.getDefaultDisplay();
//        DisplayMetrics displayMetrics = new DisplayMetrics();
//        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1)
//            display.getRealMetrics(displayMetrics);
//        else display.getMetrics(displayMetrics);

//        sNavigationBarHeight = displayMetrics.heightPixels - getDisplayHeight(display);

        Resources rs = context.getResources();
        int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
        if (id > 0) {
            if (checkDeviceHasNavigationBar(context)) {
                if (checkDeviceHasNavigationBar2(context)) {
                    if (!navigationGestureEnabled(context)) {
                        Logger.e("ydd1==" + android.os.Build.MODEL + "==" + Build.BRAND);
                        if (!android.os.Build.MODEL.equals("COL-AL10")) {
                            sNavigationBarHeight = rs.getDimensionPixelSize(id);
                            Logger.e("ydd11==" + sNavigationBarHeight);
                        } else {
                            Logger.e("ydd9==" + android.os.Build.MODEL + "==" + Build.BRAND);
                        }
                    } else {
                        Logger.e("ydd2==" + android.os.Build.MODEL + "==" + Build.BRAND);
                    }
                } else {
                    Logger.e("ydd3==" + android.os.Build.MODEL + "==" + Build.BRAND);
                    if (!navigationGestureEnabled(context)) {
                        Logger.e("ydd6==" + android.os.Build.MODEL + "==" + Build.BRAND);
                        if (Build.BRAND.equals("OPPO")) {
                            Logger.e("ydd13==" + android.os.Build.MODEL);
                        } else {
                            if (!android.os.Build.MODEL.equals("COL-AL10")) {
                                sNavigationBarHeight = rs.getDimensionPixelSize(id);
                                Logger.e("ydd10==" + sNavigationBarHeight);
                            } else {
                                Logger.e("ydd7==" + android.os.Build.MODEL + "==" + Build.BRAND);
                            }
                        }

                    } else {
                        Logger.e("ydd8==" + android.os.Build.MODEL + "==" + Build.BRAND);
                    }
                }
            } else {
                Logger.e("ydd4==" + android.os.Build.MODEL + "==" + Build.BRAND);
            }
        } else {
            Logger.e("ydd5==" + android.os.Build.MODEL + "==" + Build.BRAND);
        }
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Field field = clazz.getField("status_bar_height");
            int x = Integer.parseInt(field.get(clazz.newInstance()).toString());
            sStatusBarHeight = context.getResources().getDimensionPixelSize(x);
            Logger.e("ydd12==" + sNavigationBarHeight);
        } catch (Throwable ignored) {
        }
    }

    public static boolean checkDeviceHasNavigationBar2(Context activity) {
        //通过判断设备是否有返回键、菜单键(不是虚拟键,是手机屏幕外的按键)来确定是否有navigation bar
        boolean hasMenuKey = ViewConfiguration.get(activity)
                .hasPermanentMenuKey();
        boolean hasBackKey = KeyCharacterMap
                .deviceHasKey(KeyEvent.KEYCODE_BACK);

        if (!hasMenuKey && !hasBackKey) {
            // 做任何你需要做的,这个设备有一个导航栏
            return true;
        }
        return false;
    }

    /**
     * @param context app Context
     * @return false 表示使用的是虚拟导航键(NavigationBar)， true 表示使用的是手势， 默认是false
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static boolean navigationGestureEnabled(Context context) {
        int val = Settings.Global.getInt(context.getContentResolver(), NAVIGATION_GESTURE, NAVIGATION_GESTURE_OFF);
        return val != NAVIGATION_GESTURE_OFF;
    }

    public static boolean checkDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            //do something
        }
        return hasNavigationBar;
    }

    private static int getDisplayHeight(Display display) {
        Point point = new Point();
        display.getSize(point);
        return point.y;
    }

    public MeasureView(Context context) {
        this(context, null, 0);
    }

    public MeasureView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MeasureView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        measureScreenSize(context);
    }
}